﻿using System;
using System.Xml;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Runtime.InteropServices;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace Version3.SharePoint
{
    /// <summary>
    /// simple web control to be placed on a display form
    /// that will mark the current item as read, if it
    /// can be detected
    /// </summary>
    [CLSCompliant(false)]
    [Guid("F89B7F74-95FC-4304-88A4-52AFD3D8F8AB")]
    [ToolboxData("<{0}:ReadUnreadMarkItemRead runat=server></{0}:ReadUnreadMarkItemRead>"),
    XmlRoot(Namespace = "Version3.SharePoint")]
    public class ReadUnreadMarkItemRead : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private string _ItemIDQSValueName = "ID";
        private string _FieldName = string.Empty;
        private Guid _ListID = Guid.Empty;

        /// <summary>
        /// the name of the query string value that is
        /// the item id, normally ID
        /// </summary>
        [WebBrowsable(true)]
        public string ItemIDQSValueName
        {
            get
            {
                return _ItemIDQSValueName;
            }
            set
            {
                _ItemIDQSValueName = value;
            }
        }

        /// <summary>
        /// Optional name of the read/unread marks field
        /// </summary>
        [WebBrowsable(true)]
        public string FieldName
        {
            get
            {
                return _FieldName;
            }
            set
            {
                _FieldName =  value;
            }
        }

        /// <summary>
        /// Optional Guid of the source list
        /// </summary>
        [WebBrowsable(true)]
        public string ListID
        {
            get
            {
                return _ListID.ToString("B");
            }
            set
            {
                _ListID = new Guid(value);
            }
        }

        private ReadUnreadMarksDataField FindFieldOnList(string fieldName, SPList sourceList)
        {
            ReadUnreadMarksDataField returnValue = null;
            if (string.IsNullOrEmpty(fieldName))
            {
                foreach(SPField tempField in sourceList.Fields)
                {
                    returnValue = tempField as ReadUnreadMarksDataField;
                    if (null != returnValue) break;
                }
            }
            else
            {
                returnValue = sourceList.Fields[fieldName] as ReadUnreadMarksDataField;
            }
            return returnValue;
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                try
                {
                    //Find the list first
                    SPList thisList = null;
                    if (_ListID != Guid.Empty)
                    {
                        SPWeb thisWeb = SPControl.GetContextWeb(this.Context);
                        thisList = thisWeb.Lists[_ListID];
                    }
                    else
                    {
                        thisList = SPContext.Current.List;
                    }
                    if (null != thisList)
                    {
                        ReadUnreadMarksDataField markField = FindFieldOnList(_FieldName, thisList);
                        if (null != markField)
                        {
                            //Get the ID
                            int itemId = int.Parse(this.Context.Request.QueryString[_ItemIDQSValueName]);
                            SPListItem listItem = thisList.GetItemById(itemId);
                            //Ensure the user
                            SPUser spMe = UtilityMethods.EnsureUser(System.Web.HttpContext.Current.User.Identity.Name);
                            //Write the read mark
                            UtilityMethods.MarkItemAsRead(spMe, listItem, markField);
                        }
                    }
                }
                catch (Exception renderError)
                {
                    System.Diagnostics.Trace.WriteLine(renderError.Message);
                }
            }

        }
    }
}
